<?php

namespace app\member\controller\api;

use app\ApiController;
use think\Db;
use think\facade\Lang;
use think\facade\Env;
use app\member\model\UsersModel;
use app\member\model\WithdrawModel;
use app\member\model\AccountLogModel;
use app\distribution\model\DividendModel;
use app\shop\model\OrderModel;
use app\shop\model\BonusModel;


/*------------------------------------------------------ */
//-- 会员相关API
/*------------------------------------------------------ */

class Users extends ApiController
{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->checkLogin();//验证登陆
        $this->Model = new UsersModel();
    }
    /*------------------------------------------------------ */
    //-- 获取登陆会员信息
    /*------------------------------------------------------ */
    public function getInfo()
    {
        $return['info'] = $this->userInfo;
        $return['code'] = 1;
        return $this->ajaxReturn($return);
    }

    /*------------------------------------------------------ */
    //-- 修改用户密码
    /*------------------------------------------------------ */
    public function editPwd()
    {
        $res = $this->Model->editPwd(input(), $this);
        if ($res !== true) return $this->error($res);
        return $this->success('密码已重置，请用新密码登陆.');
    }
    /*------------------------------------------------------ */
    //-- 修改用户密码
    /*------------------------------------------------------ */
    public function editPayPwd()
    {
        $pay_password = input('password','','trim');
        if (empty($pay_password))  return $this->error('请输入新的支付密码.');
        $this->checkCode('edit_pay_pwd',$this->userInfo['mobile'],input('code'));//验证短信验证
        $data['pay_password'] = f_hash($pay_password);
        if ($data['pay_password'] == $this->userInfo['pay_password']){
            return $this->error('新密码与旧密码一致，无需修改.');
        }
        $res = $this->Model->where('user_id', $this->userInfo['user_id'])->update($data);
        if ($res < 1) {
            return $this->error('未知错误，处理失败.');
        }
        // $this->_log($this->userInfo['user_id'], '用户修改支付密码.', 'member');
        return $this->success('支付密码修改成功.');
    }
    //*------------------------------------------------------ */
    //-- 绑定会员手机
    /*------------------------------------------------------ */
    public function bindMobile()
    {
        $this->checkCode('login', input('mobile'), input('code'));//验证短信验证
        $res = $this->Model->bindMobile(input(), $this);
        if ($res !== true) return $this->error($res);
        return $this->success('绑定手机成功.');
    }
    /*------------------------------------------------------ */
    //-- 获取会员中心首页所需数据
    /*------------------------------------------------------ */
    public function getCenterInfo()
    {
        $OrderModel = new OrderModel();
        $return['orderStats'] = $OrderModel->userOrderStats($this->userInfo['user_id']);
        $return['userInfo'] = $this->userInfo;
        $return['userInfo']['pmobile'] = Db::table('users')->where('user_id',$this->userInfo['pid'])->value('mobile');
        $level_type = Db::name('user_region')->where(['region'=>$this->userInfo['proxy']])->where('user_id',$this->userInfo['user_id'])->value('level');
        if($level_type == 1){
            $level_type = '省代';
            $return['userInfo']['region'] = Db::name('bs_province')->where('PROVINCE_CODE',$this->userInfo['proxy'])->value('PROVINCE_NAME');
        }elseif($level_type == 2){
            $level_type = '市代';
            $return['userInfo']['region'] = Db::name('bs_city')->where('CITY_CODE',$this->userInfo['proxy'])->value('CITY_NAME');
        }elseif($level_type  == 3){
            $level_type = '区代';
            $return['userInfo']['region'] = Db::name('bs_area')->where('AREA_CODE',$this->userInfo['proxy'])->value('AREA_NAME');
        }elseif($level_type  == 4){
            $level_type = '镇代';
            $return['userInfo']['region'] = Db::name('bs_street')->where('STREET_CODE',$this->userInfo['proxy'])->value('STREET_NAME');
        }else{
            $level_type = '无';
            $return['userInfo']['region'] = '无';
        }
        $return['userInfo']['level_type'] = $level_type;
        $BonusModel = new BonusModel();
        $bonus = $BonusModel->getListByUser();
        $return['unusedNum'] = $bonus['unusedNum'];
        $return['code'] = 1;
        return $this->ajaxReturn($return);
    }

    //获取省市区地址
    public function getregion(){
        $level = input('get.level/d');
        $parent_code = input('get.parent_code/d');
        $return['code'] = 1;
        switch ($level)
        {
        case 1:
            // 查询省的数据
            $return['data'] = Db::table('bs_province')->where('DATA_STATE',1)->field('PROVINCE_CODE,PROVINCE_NAME')->select();
            $return['goods'] = Db::table('shop_goods')->where('isputaway',1)->where('is_type',$level)->where('is_delete',0)->find();
            break;
        case 2:
            // 查询市的数据
            $return['data'] = Db::table('bs_city')->where('DATA_STATE',1)->field('CITY_CODE,CITY_NAME')->where('PROVINCE_CODE',$parent_code)->select();
            $return['goods'] = Db::table('shop_goods')->where('isputaway',1)->where('is_type',$level)->where('is_delete',0)->find();
            break;
        case 3:
            // 查询区的数据
            $return['data'] = Db::table('bs_area')->where('DATA_STATE',1)->field('AREA_CODE,AREA_NAME')->where('CITY_CODE',$parent_code)->select();
            $return['goods'] = Db::table('shop_goods')->where('isputaway',1)->where('is_type',$level)->where('is_delete',0)->find();
            break;
        case 4:
            // 查询镇的数据
            $return['data'] = Db::table('bs_street')->where('DATA_STATE',1)->field('STREET_CODE,STREET_NAME')->where('AREA_CODE',$parent_code)->select();
            $return['goods'] = Db::table('shop_goods')->where('isputaway',1)->where('is_type',$level)->where('is_delete',0)->find();
            break;
        default:
            $return['code'] = 0;
            $return['data'] = '';
        }
        
        return $this->ajaxReturn($return);
    }


    /*------------------------------------------------------ */
    //-- 获取会员中心店铺数据
    /*------------------------------------------------------ */
    public function getUserRegion()
    {
        $map['user_id'] =$this->userInfo['user_id'];
        $res['code'] = 1;
        $user_store = Db::name('user_region')->where($map)->where('status','in',[0,1])->find();
        if(!empty($user_store)){
            if($user_store['status'] == 1){
                $msg = '您已通过审核';
            }else{
                $msg = '您已有待审核信息';
            }
            $res['code'] = 0;
            $res['msg'] = $msg;
            $isbuy = 0;
            if(empty($user_store['order_id'])){
                //查询订单
                $allorder = Db::table('shop_order_info')->where('user_id',$this->userInfo['user_id'])->where('pay_status',1)->select();
                foreach($allorder as $orderv){
                    $goods = Db::table('shop_goods')->where('goods_id',$orderv['buy_goods_id'])->where('is_type','<>',0)->find();
                    if($goods){//已购买购买代理产品
                        if($user_store['level'] == $goods['is_type']){
                            Db::name('user_region')->where('id',$user_store['id'])->update(['order_id'=>$orderv['order_id']]);
                            $isbuy = 1;
                            break;
                        }
                    }
                }
                if($isbuy == 0){
                    $res['code'] = 1;
                    Db::name('user_region')->where($map)->where('status',0)->delete();
                }else{
                    $msg = '您已有待审核信息';
                }
                
                
            }
        }else{
        }
        return $this->ajaxReturn($res);
    }
    /*------------------------------------------------------ */
    //-- 获取会员中心店铺数据
    /*------------------------------------------------------ */
    public function getStore()
    {
        $map['user_id'] =$this->userInfo['user_id'];
        $map['status'] = 0;
        $user_store = Db::name('distribution_store')->where($map)->find();
        if(!empty($user_store)){
            $res['code'] = 0;
            $res['msg'] = '您已有待审核信息';
        }else{
            $res['code'] = 1;
        }
        return $this->ajaxReturn($res);
    }
    /*------------------------------------------------------ */
    //-- 获取分享二维码
    /*------------------------------------------------------ */
    public function myCode()
    {
        $file_path = config('config._upload_') . 'qrcode/' . substr($this->userInfo['user_id'], -1) . '/';
        $file = $file_path . $this->userInfo['user_id'] . '.png';
        if (file_exists($file) == false) {
            include EXTEND_PATH . 'phpqrcode/phpqrcode.php';//引入PHP QR库文件
            $QRcode = new \phpqrcode\QRcode();
            $value = config('config.host_path') . '/member/passport/register.html?share_token=' . $this->userInfo['user_id'];
            makeDir($file_path);
            $png = $QRcode::png($value, $file, "L", 10, 1, 2, true);
        }
        $return['file'] = config('config.host_path') . '/' . trim($file, '.');
        $return['code'] = 1;
        return $this->ajaxReturn($return);
    }
    /*------------------------------------------------------ */
    //-- 获取分享商品二维码
    /*------------------------------------------------------ */
    public function goodsCode()
    {
        $goods_id = input('goods_id', 0, 'intval');
        $file_path = config('config._upload_') . 'goods_qrcode/' . $goods_id . '/';
        $file = $file_path . $this->userInfo['token'] . '.png';
        if (file_exists($file) == false) {
            include EXTEND_PATH . 'phpqrcode/phpqrcode.php';//引入PHP QR库文件
            $QRcode = new \phpqrcode\QRcode();
            $value = config('config.host_path') . url('shop/goods/info', ['id' => $goods_id, 'share_token' => $this->userInfo['token']]);
            makeDir($file_path);
            $png = $QRcode::png($value, $file, "L", 10, 1, 2, true);
        }
        $return['file'] = config('config.host_path') . '/' . trim($file, '.');
        $return['code'] = 1;
        return $this->ajaxReturn($return);
    }
    /*------------------------------------------------------ */
    //-- 获取分享商品二维码
    /*------------------------------------------------------ */
    public function storeCode()
    {
        $file_path = config('config._upload_') . 'store_qrcode/' . substr($this->userInfo['user_id'], -1) . '/';
        $file = $file_path . $this->userInfo['token'] . '.png';
//        if (file_exists($file) == false) {
            include EXTEND_PATH . 'phpqrcode/phpqrcode.php';//引入PHP QR库文件
            $QRcode = new \phpqrcode\QRcode();
            $value = config('config.host_path') . url('shop/index/store_pay', ['user_id' => $this->userInfo['user_id'], 'share_token' => $this->userInfo['token']]);
            makeDir($file_path);
            $png = $QRcode::png($value, $file, "L", 10, 1, 2, true);
//        }
        $data = Db::name('distribution_store')->where(['user_id'=>$this->userInfo['user_id']])->field('store_name,user_id,store_logo_img')->find();
        $return['file'] = config('config.host_path') . '/' . trim($file, '.');
        $return['code'] = 1;
        $return['data'] = $data;
//        dump($return);
        return $this->ajaxReturn($return);
    }

    /*------------------------------------------------------ */
    //-- 获取会员帐号数据
    /*------------------------------------------------------ */
    public function getAccount()
    {
        $return['account'] = $this->userInfo['account'];
        //计算提现中金额，即为冻结金额
        $WithdrawModel = new WithdrawModel();
        $where[] = ['user_id', '=', $this->userInfo['user_id']];
        $where[] = ['status', '=', 0];
        $return['frozen_amount'] = $WithdrawModel->where($where)->sum('amount');
        //end
        $DividendModel = new DividendModel();
        //今天收益
        unset($where);
        $where[] = ['dividend_uid', '=', $this->userInfo['user_id']];
        $where[] = ['status', 'in', [1, 2, 3, 9]];
        $where[] = ['add_time', '>=', strtotime("today")];
        $return['today_income'] = $DividendModel->where($where)->sum('dividend_amount');
        //end
        //本月收益
        unset($where);
        $where[] = ['dividend_uid', '=', $this->userInfo['user_id']];
        $where[] = ['status', 'in', [1, 2, 3, 9]];
        $where[] = ['add_time', '>', strtotime(date('Y-m-01', strtotime('-1 month')))];
        $return['month_income'] = $DividendModel->where($where)->sum('dividend_amount');

        //end
        $return['withdraw_status'] = settings('withdraw_status');//获取是否开启提现
        $return['code'] = 1;
        return $this->ajaxReturn($return);
    }
    /*------------------------------------------------------ */
    //-- 获取会员帐户变动日志
    /*------------------------------------------------------ */
    public function getAccountLog()
    {
        $type = input('type', 'order', 'trim');
        $time = input('time', '', 'trim');
        if (empty($time)) {
            $time = date('Y年m月');
        }
        $return['time'] = $time;
        $_time = strtotime(str_replace(array('年', '月'), array('-', ''), $time));
        $return['code'] = 1;
        $AccountLogModel = new AccountLogModel();
        $where[] = ['user_id', '=', $this->userInfo['user_id']];
        $where[] = ['change_time', 'between', array($_time, strtotime(date('Y-m-t', $_time)) + 86399)];


        $rows = $AccountLogModel->where($where)->order('change_time DESC')->select();
        foreach ($rows as $key => $row) {

            if ($row['balance_money'] > 0) {
                $return['b_income'] += $row['balance_money'];
            } else {
                $return['b_expend'] += $row['balance_money'] * -1;
            }

            if ($row['use_integral'] > 0) {
                $return['i_income'] += $row['use_integral'];
            } else {
                $return['i_expend'] += $row['use_integral'] * -1;
            }
            if ($row['total_dividend'] > 0) {
                $return['y_income'] += $row['total_dividend'];
            } else {
                $return['y_expend'] += $row['total_dividend'] * -1;
            }
            if ($row['bean_value'] > 0) {
                $return['bean_value'] += $row['bean_value'];
            } else {
                $return['bean_value'] += $row['bean_value'];
            }
            if ($row['d_use_integral'] > 0) {
                $return['d_use_integral'] += $row['d_use_integral'];
            } else {
                $return['d_use_integral'] += $row['d_use_integral'];
            }

            if ($type == 'order'){
                if ($row['change_type'] != 3){
                    continue;
                }
            }elseif($type == 'brokerage'){
                if ($row['change_type'] != 4){
                    continue;
                }
            }elseif($type == 'withdraw'){
                if ($row['change_type'] != 5){
                    continue;
                }
            }elseif($type == 'use_integral'){
                if ($row['use_integral'] > 0) {
                    $row['value'] = '+' . $row['use_integral'];
                } elseif ($row['use_integral'] < 0){
                    $row['value'] = $row['use_integral'];
                }
                if ($row['use_integral'] == 0){
                    continue;
                }
            }elseif($type == 'balance_money'){
                if ($row['balance_money'] > 0) {
                    $row['value'] = '+' . $row['balance_money'];
                } elseif ($row['balance_money'] < 0) {
                    $row['value'] = $row['balance_money'];
                }
                if ($row['balance_money'] == 0){
                    continue;
                }
            }elseif($type == 'total_dividend'){
                if ($row['total_dividend'] > 0) {
                    $row['value'] = '+' . $row['total_dividend'];
                } elseif ($row['total_dividend'] < 0) {
                    $row['value'] = $row['total_dividend'];
                }
                if ($row['total_dividend'] == 0){
                    continue;
                }
            }elseif($type == 'bean_value'){
                if ($row['bean_value'] > 0) {
                    $row['value'] = '+' . $row['bean_value'];
                } elseif ($row['bean_value'] < 0) {
                    $row['value'] = $row['bean_value'];
                }
                if ($row['bean_value'] == 0){
                    continue;
                }
            }elseif($type == 'd_use_integral'){
                if ($row['d_use_integral'] > 0) {
                    $row['value'] = '+' . $row['d_use_integral'];
                } elseif ($row['d_use_integral'] < 0) {
                    $row['value'] = $row['d_use_integral'];
                }
                if ($row['d_use_integral'] == 0){
                    continue;
                }
            }
            $row['_time'] = timeTran($row['change_time']);
            $return['list'][] = $row;
        }
        return $this->ajaxReturn($return);
    }
    /*------------------------------------------------------ */
    //-- 获取会员佣金日志
    /*------------------------------------------------------ */
    public function getDividendLog()
    {
        $type = input('type', 'all_balance_money', 'trim');
        $time = input('time', '', 'trim');
        if (empty($time)) {
            $time = date('Y年m月');
        }
        $return['time'] = $time;
        $_time = strtotime(str_replace(array('年', '月'), array('-', ''), $time));
        $return['code'] = 1;
        $DividendModel = new DividendModel();
        $where[] = ['dividend_uid', '=', $this->userInfo['user_id']];
        switch ($type) {
            case 'all_balance_money'://佣金
                $where[] = ['add_time', 'between', array($_time, strtotime(date('Y-m-t', $_time)) + 86399)];
                $where[] = ['dividend_amount', '<>', 0];
                break;
            case 'wait_balance_money'://等待分佣金
                $where[] = ['add_time', 'between', array($_time, strtotime(date('Y-m-t', $_time)) + 86399)];
                $where[] = ['dividend_amount', '<>', 0];
                $where[] = ['status', '=', 3];
                break;
            case 'arrival_balance_money'://金币已到帐明细
                $where[] = ['add_time', 'between', array($_time, strtotime(date('Y-m-t', $_time)) + 86399)];
                $where[] = ['dividend_amount', '<>', 0];
                $where[] = ['status', '=', 9];
                break;
            case 'cancel_balance_money'://金币失效明细
                $where[] = ['add_time', 'between', array($_time, strtotime(date('Y-m-t', $_time)) + 86399)];
                $where[] = ['dividend_amount', '<>', 0];
                $where[] = ['status', 'in', [1, 4]];
                break;
            case 'dividend_bean'://旅游豆
                $where[] = ['dividend_bean', '<>', 0];
                $where[] = ['status', '=', 9];
                $where[] = ['is_hide', '=', 0];
                $where[] = ['update_time', '>', time() - 172800];//只显示最近两到帐的佣金
                break;
            default:
                return $this->error('类型错误.');
                break;
        }
        $return['income'] = 0;
        $rows = $DividendModel->where($where)->order('add_time DESC')->select();

        $lang = lang('order');
        foreach ($rows as $key => $row) {
            $income = $row['dividend_amount'] > 0 ? $row['dividend_amount'] : $row['dividend_bean'];
            $return['income'] += $income;
            $row['_time'] = timeTran($row['add_time']);
            $row['value'] = $income;
            $row['nick_name'] = userInfo($row['buy_uid']);
            $row['status'] = $lang['ds'][$row['status']];
            $return['list'][] = $row;
        }
        return $this->ajaxReturn($return);
    }
    /*------------------------------------------------------ */
    //-- 修改会员信息
    /*------------------------------------------------------ */
    public function editInfo()
    {
        $imgfile = input('imgfile');
        if (empty($imgfile) == false) {
            $file_path = config('config._upload_') . 'headimg/' . substr($this->userInfo['user_id'], -1) . '/';
            makeDir($file_path);
            $file_name = $file_path . random_str(12) . '.jpg';
            file_put_contents($file_name, base64_decode(str_replace('data:image/jpeg;base64,', '', $imgfile)));
            $upArr['headimgurl'] = trim($file_name, '.');
        }
        $upArr['nick_name'] = input('nick_name', '', 'trim');
        if (empty($upArr['nick_name']) == true) {
            return $this->error('请填写用户昵称.');
        }
        $where[] = ['nick_name', '=', $upArr['nick_name']];
        $where[] = ['user_id', '<>', $this->userInfo['user_id']];
        $count = $this->Model->where($where)->count('user_id');
        if ($count > 0) return '昵称：' . $upArr['nick_name'] . '，已存在.';
        $upArr['signature'] = input('signature', '', 'trim');
        $upArr['sex'] = input('sex', '男', 'trim');
        $upArr['sex'] = $upArr['sex'] == '男' ? 1 : 0;
        // $upArr['birthday'] = input('birthday', '', 'trim');
        $upArr['show_mobile'] = input('show_mobile', 0, 'intval');
        $res = $this->Model->upInfo($this->userInfo['user_id'], $upArr);
        if ($res < 1) {
            @unlink($file_name);
            return $this->error('修改用户信息失败，请重试.');
        }
        return $this->success('修改成功.');
    }
    /*------------------------------------------------------ */
    //-- 获取远程会员头像到本地
    /*------------------------------------------------------ */
    public function getHeadImg()
    {
        $headimgurl = $this->userInfo['headimgurl'];
        if (empty($headimgurl) == false) {
            if (strstr($headimgurl, 'http')) {
                $file_path = config('config._upload_') . 'headimg/' . substr($this->userInfo['user_id'], -1) . '/';
                makeDir($file_path);
                $file_name = $file_path . random_str(12) . '.jpg';
                file_put_contents($file_name, file_get_contents($this->userInfo['headimgurl']));
                $upArr['headimgurl'] = $headimgurl = trim($file_name, '.');
                (new UsersModel)->upInfo($this->userInfo['user_id'], $upArr);
            }
        }
        $return['headimgurl'] = $headimgurl;
        $return['code'] = 1;
        return $this->ajaxReturn($return);
    }

    public function get_province(){
        $province = Db::name('main_region')->where('level_type',1)->field('id,name,level_type')->select(); //获取省数据
        $province = json_encode($province);
        return $province;
    }

    public function get_city(){
        $province = input('id');
        if($province){
            $city = Db::name('main_region')->where('pid',$province)->field('id,name,level_type')->select(); //获取省数据
        }

        $city = json_encode($city);
        return $city;
    }

    public function get_district(){
        $province = input('id');
        if($province){
            $district = Db::name('main_region')->where('pid',$province)->field('id,name,level_type')->select(); //获取省数据
        }
        $district = json_encode($district);
        return $district;
    }

    /*------------------------------------------------------ */
    //-- 获取签到数据
    /*------------------------------------------------------ */
    public function getSignData(){

        $year = input('year',date('Y'));
        $month = input('month',date('n'));

        $data = Db::table('users_sign')->where(['user_id'=>$this->userInfo['user_id'],'year'=>$year,'month'=>$month])->find();
        if(!$data){
            $data['days'] = '';
        }
        $return['code'] = 1;
        $return['data'] = $data;
        return $this->ajaxReturn($return);
    }
    /*------------------------------------------------------ */
    //-- 今日签到
    /*------------------------------------------------------ */
    public function doSign(){
        $year = date('Y');
        $month = date('n');
        $day = date('d');
        $AccountLogModel = new AccountLogModel();
        $sigin = settings('sign_integral');
        $sign_day = settings('sign_day');
        $user_id = $this->userInfo['user_id'];
        $sign_day =$this->userInfo['reg_time'] + 86400 * $sign_day;
        if(time() > $sign_day){
            $this->error('已过期,无法再签到！');
        }
        
        $sign_in = settings('sign_in');
        if(empty($sign_in)) $this->error('签到已关闭！');
        $data = Db::table('users_sign')->where(['user_id'=>$user_id,'year'=>$year,'month'=>$month])->find();
        if($data&&isset($data['days'])){
            $tmp_arr = explode(',',$data['days']);
            if(in_array($day, $tmp_arr)){
                $this->error('今天已经签到,请勿重复签到！');
            }
        }



        Db::startTrans();
        if($data){
            //本月数据已有,直接更新
            $upData = ['days'=>$data['days'].','.$day,'last_time'=>time(),'score'=>$sigin];
            $res = Db::table('users_sign')->where(['id'=>$data['id']])->update($upData);
        }else{
            //本月数据没有,进行插入
            $inData = [
                'user_id' => $user_id,
                'year'    => $year,
                'month'   => $month,
                'days'    => $day,
                'score'   => $sigin,
                'last_time'=> time()
            ];
            $res = Db::table('users_sign')->insert($inData);
        }

        if(!$res){
            Db::rollback();
            $this->error('签到失败,请联系管理员');
        }

        //签到成功，加星券
        $accData['change_desc'] = '签到获得星券';
        $accData['change_type'] = 10;
        $accData['by_id'] = 0;
        $accData['use_integral'] = $sigin;
        $res = $AccountLogModel->change($accData,$user_id,false);

        if(!$res){
            Db::rollback();
            $this->error('签到失败,星券处理异常');
        }

        Db::commit();
        $return['code'] = 1;
        $return['msg'] = '签到成功';
        $return['score'] = $sigin;
        return $this->ajaxReturn($return);
    }
   /*------------------------------------------------------ */
    //-- 获签到记录
    /*------------------------------------------------------ */
    public function getSign(){
        $data = Db::table('users_sign')->where('user_id',$this->userInfo['user_id'])->order('year','asc')->order('month','asc')->select();
        foreach($data as $k=>$value){
            $day = explode(',',$value['days']);
            foreach($day as $vu){
                $newdata[] = $data[$k]['year'].'-'.$data[$k]['month'].'-'.$vu;
            }
        }
        $return['code'] = 1;
        $return['data'] = $newdata;
        return $this->ajaxReturn($return);
    }


    // 余额转赠
    public function givemoney(){
        $user_id = input('user_id');
        $money = input('money');
        $password = input('password');
        if (empty($user_id))  return $this->error('请输入用户ID.');
        if (empty($money))  return $this->error('请输入金额.');
        if (empty($password))  return $this->error('请输入支付密码.');
        if($this->userInfo['account']['balance_money'] < $money){
            return $this->error('余额不足.');
        }
        if( $money<1 or $money%10){
            return $this->error('转赠必须为10的倍数.');
        }
        if($this->userInfo['pay_password']  != f_hash($password)){
            return $this->error('支付密码错误.');
        }
        $haveuser = Db::table('users')->where('user_id',$user_id)->find();
        if(empty($haveuser)){
            $haveuser = Db::table('users')->where('mobile',$user_id)->find();
            if(empty($haveuser)){
                return $this->error('用户不存在.');
            }
        }
        Db::startTrans();//启动事务
        $AccountLogModel = new AccountLogModel();
        $changedata['change_desc'] = '余额转赠给'.$haveuser['nick_name'];
        $changedata['change_type'] = 2;
        $changedata['by_id'] = $this->userInfo['user_id'];
        $changedata['balance_money'] = $money * -1;
        $res = $AccountLogModel->change($changedata, $this->userInfo['user_id'], false);
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error('系统繁忙.');
        }
        $changedata2['change_desc'] = '获得'.$this->userInfo['nick_name'].'余额转赠';
        $changedata2['change_type'] = 2;
        $changedata2['by_id'] = $this->userInfo['user_id'];
        $changedata2['balance_money'] = $money;
        $res2 = $AccountLogModel->change($changedata2, $haveuser['user_id'], false);
        if ($res2 !== true) {
            Db::rollback();// 回滚事务
            return $this->error('系统繁忙.');
        }
        Db::commit();// 提交事务
        $return['code'] = 1;
        $return['msg'] = '转赠成功';
        return $this->ajaxReturn($return);
    }
}
